package com.lh.controller;

import com.lh.entity.*;
import com.lh.service.AddressService;
import com.lh.service.CartService;
import com.lh.service.GoodsService;
import com.lh.service.OrdersService;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

/**
 * @Author: LuoHang
 * @Date: 2021/2/16 0:45
 * @Description
 */
@Controller
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CartService cartService;

    /*
    后台操作
     */

    /**
     * 获取订单页面
     *
     * @return 视图模型
     */
    @RequestMapping("/ordersListHtml")
    public ModelAndView ordersListHtml() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("merchant/orders_list");
        return modelAndView;
    }

    /**
     * 待处理的订单页面
     *
     * @return 视图模型
     */
    @RequestMapping("/ordersUnDealListHtml")
    public ModelAndView ordersUnDealListHtml() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("merchant/orders_unDeal_list");
        return modelAndView;
    }

    /**
     * 获取订单
     * 前后台通用
     *
     * @param request 请求对象
     * @return lay_ui需要的数据格式
     */
    @RequestMapping("/getOrders")
    @ResponseBody
    public Map<String, Object> getOrders(HttpServletRequest request) {
        String merchantId = request.getParameter("merchantId");
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
        String orderStatus = request.getParameter("orderStatus");
        //订单id
        String id = request.getParameter("id");
        Map<String, Object> query = new HashMap<>(8);
        if (!StringUtils.isNullOrEmpty(merchantId)) {
            query.put("merchantId", Integer.valueOf(merchantId));
        }
        //怎么解决id用户输成非数字字符串
        if (!StringUtils.isNullOrEmpty(id)) {
            query.put("id", id);
        }
        String test = "请选择";
        if (!StringUtils.isNullOrEmpty(orderStatus) && !test.equals(orderStatus)) {
            query.put("orderStatus", Integer.parseInt(orderStatus));
        }
        if (!StringUtils.isNullOrEmpty(page) && !StringUtils.isNullOrEmpty(limit)) {
            Integer pageInt = Integer.valueOf(page);
            Integer limitInt = Integer.valueOf(limit);
            query.put("beginSize", (pageInt - 1) * limitInt);
            query.put("limit", limitInt);
        }
        List<Orders> orders = ordersService.getOrders(query);

        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", 9);
        map.put("data", orders);
        return map;
    }

    /**
     * 订单编辑页面
     *
     * @param id 订单id
     * @return 视图模型
     */
    @RequestMapping("/ordersEditHtml")
    public ModelAndView ordersEditHtml(@RequestParam Integer id) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("id", id);
        Orders orders = ordersService.getOrdersById(map);
        Address address = addressService.getAddressById(orders.getAddressId());
        List<OrdersInfo> ordersInfoList = orders.getOrdersInfoList();
        List<Goods> goodsList = new ArrayList<>();
        for (OrdersInfo ordersInfo : ordersInfoList) {
            goodsList.add(goodsService.getGoodsById(ordersInfo.getGoodsId()));
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("orders", orders);
        modelAndView.addObject("address", address);
        modelAndView.addObject("goodsList", goodsList);
        modelAndView.setViewName("merchant/orders_edit");
        return modelAndView;
    }

    /**
     * 订单信息修改
     *
     * @param request 请求对象
     * @param id      被修改的订单对应的id
     * @return 是否修改成功
     */
    @RequestMapping("/updateOrders")
    @ResponseBody
    public Map<String, Object> updateOrders(HttpServletRequest request, @RequestParam Integer id) {
        String logisticsType = request.getParameter("logisticsType");
        String orderStatus = request.getParameter("orderStatus");
        Map<String, Object> query = new HashMap<>(5);
        query.put("id", id);
        Orders orders = ordersService.getOrdersById(query);
        //关于shipAddress没有做更新 如果订单没有发货就可以进行修改地址 如果已经发货就不能进行地址修改
        //物流方式选择
        query.put("gmtModified", new Timestamp(System.currentTimeMillis()));
        if (!StringUtils.isNullOrEmpty(logisticsType) && !logisticsType.equals(orders.getLogisticsType())) {
            query.put("logisticsType", logisticsType);
        }
        if (!StringUtils.isNullOrEmpty(orderStatus) && Integer.parseInt(orderStatus) != orders.getOrderStatus()) {
            query.put("orderStatus", orderStatus);
        }

        int count = ordersService.updateOrders(query);
        Map<String, Object> map = new HashMap<>(1);
        map.put("data", count > 0 ? "修改成功" : "修改失败");
        return map;
    }

    /**
     * 根据id删除对应的订单
     *
     * @param id 订单对应的id
     * @return 是否删除成功
     */
    @RequestMapping("/deleteOrdersById")
    @ResponseBody
    public Map<String, Object> deleteOrdersById(@RequestParam Integer id) {
        int count = ordersService.deleteOrdersById(id);
        Map<String, Object> map = new HashMap<>(1);
        map.put("data", count > 0 ? "删除成功" : "删除失败");
        return map;
    }


    /*
    前台个人订单
     */

    /**
     * 前台个人订单页面
     *
     * @return 视图模型
     */
    @RequestMapping("/getOrderHtml")
    public ModelAndView getOrderHtml(@RequestParam Integer userId) {
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> query = new HashMap<>(4);
        query.put("userId", userId);
        List<Orders> orders = ordersService.getOrders(query);
        modelAndView.addObject("ordersList", orders);
        modelAndView.setViewName("order");
        return modelAndView;
    }

    /**
     * 前台订单详情查看页面
     *
     * @param id 订单id
     * @return 视图模型
     */
    @RequestMapping("/orderViewHtml")
    public ModelAndView orderViewHtml(@RequestParam Integer id) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("id", id);
        Orders orders = ordersService.getOrdersById(map);
        Address address = addressService.getAddressById(orders.getAddressId());
        List<OrdersInfo> ordersInfoList = orders.getOrdersInfoList();
        List<Goods> goodsList = new ArrayList<>();
        for (OrdersInfo ordersInfo : ordersInfoList) {
            goodsList.add(goodsService.getGoodsById(ordersInfo.getGoodsId()));
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("orders", orders);
        modelAndView.addObject("address", address);
        modelAndView.addObject("goodsList", goodsList);
        modelAndView.setViewName("order_view");
        return modelAndView;
    }

    /**
     * 订单完成后的评价页面
     *
     * @return 视图模型
     */
    @RequestMapping("/ordersCommentHtml")
    public ModelAndView commentHtml() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("order_comment");
        return modelAndView;
    }

    /**
     * 订单创建
     *
     * @return 是否创建成功
     */
    @RequestMapping("/createOrders")
    public ModelAndView createOrders(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");

        String orderNumber = System.currentTimeMillis() + "_u" + user.getId();

        Address address = addressService.getAddressByIdOn(user.getId());

        Orders orders = new Orders();
        orders.setOrderNumber(orderNumber);
        orders.setUserId(user.getId());
        orders.setAddressId(address.getId());
        ordersService.addOrders(orders);

        orders = ordersService.getOrderByOrderNum(orderNumber);

        Enumeration<String> e = request.getParameterNames();
        BigDecimal sum = BigDecimal.ZERO;
        while (e.hasMoreElements()){
            String name = e.nextElement();
            Integer id = Integer.parseInt(request.getParameter(name));
            HashMap<String,Object> map = new HashMap<>(2);
            map.put("status",0);
            map.put("id",id);
            cartService.updateCart(map);

            Cart cart = cartService.getCartById(id);

            sum = sum.add(new BigDecimal(cart.getBuyNum()).multiply(cart.getGoods().getGoodsPrice()));
            cartService.addOrdersCart(new OrdersCart(null, orders.getId(), id));

            //减去库存中的数量
            Map<String,Object> updateInfo = new HashMap<>(2);
            updateInfo.put("id",cart.getGoods().getId());
            updateInfo.put("goodsNum",cart.getGoods().getGoodsNum()-cart.getBuyNum());
            goodsService.updateGoods(updateInfo);
        }

        //计算订单总金额
        Map<String,Object> updateInfo = new HashMap<>(2);
        updateInfo.put("id",orders.getId());
        updateInfo.put("payMoney",sum);
        ordersService.updateOrders(updateInfo);

        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> query = new HashMap<>(4);
        query.put("userId", user.getId());
        List<Orders> ordersList = ordersService.getOrders(query);
        modelAndView.addObject("ordersList", ordersList);
        modelAndView.setViewName("order");
        modelAndView.addObject("address",address);
        return modelAndView;
    }
}
